//
//  QQTool.swift
//  DollarBuy
//
//  Created by 郑东喜 on 2016/11/4.
//  Copyright © 2016年 郑东喜. All rights reserved.
//  QQ第三方

import UIKit

protocol testDelegate {
    func shareSuccssWithQQCode(str:NSInteger)
}

class QQTool: NSObject,QQApiInterfaceDelegate,TencentSessionDelegate {
    
    //qq登陆代理回调
    var delegate : testDelegate?
    
    //qq授权
    var tencentOAuth = TencentOAuth()
    
    var permissionArray = NSMutableArray()
    
    
    //openid
    var qqOpenID = String()
    
    
    static let qqTool = QQTool()
    /**
     * 登录时网络有问题的回调
     */
    public func tencentDidNotNetWork() {
        print("\((#file as NSString).lastPathComponent):(\(#line)):(\("没有网络了")))")
    }

    /**
     * 登录失败后的回调
     * \param cancelled 代表用户是否主动退出登录
     */
    public func tencentDidNotLogin(_ cancelled: Bool) {
        if cancelled {
            print("用户点击取消按键,主动退出登录")
//            alertFail(message: "授权登陆失败")
        } else {
            print("其他原因， 导致登录失败")
        }
    }

    // MARK:- 登陆后回调
    public func tencentDidLogin() {
        if (tencentOAuth.accessToken != nil) {
            tencentOAuth.getUserInfo()
            
            print("\((#file as NSString).lastPathComponent):(\(#line)):(\("qq openID")))")
            print(tencentOAuth.openId)
            
            //存入本地qq openID
            guard let openID = tencentOAuth.openId else {
                return
            }
            self.qqOpenID = openID
            
            localSave.set(openID, forKey: qqopenID)
            localSave.synchronize()
            
            print("授权成功")
            let qoid = localSave.object(forKey: qqopenID) as! String
            
            print(localSave.object(forKey: wxopenID) as? String as Any)
            print(qoid)
            

            alertSuccess(message: "授权登陆成功")
            
            //登陆成功发送通知
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "qqLoginSuccess"), object: nil)
        } else {

            print("accessToken 没有获取成功")
        }
    }
    
    /**
     处理来至QQ的请求
     */
    func onReq(_ req: QQBaseReq!) {
        
    }
    
    
    /**
     0   成功
     -1  参数错误
     -2  该群不在自己的群列表里面
     -3  上传图片失败
     -4  用户放弃当前操作
     -5  客户端内部处理错误
     */
    func onResp(_ resp: QQBaseResp!) {
        print("\((#file as NSString).lastPathComponent):(\(#line))")
        if resp is SendMessageToQQResp {

            let msg = (resp as! SendMessageToQQResp)

            print(msg.result)
            
            let code = NSInteger(msg.result)!
            if code == 0 {
                print("分享成功")

                
//                alertSuccess(title: "提示", message: "分享成功")
                alertSuccess(message: "分享成功")
            } else if code == -4 {
                print("用户放弃当前操作")

                alertFail(message: "分享失败")
            } else if code == -5 {
                return
            }

        }
    }
    // MARK:- 接入代理方法
    func qqLogin() -> Void {
        tencentOAuth = TencentOAuth(appId: QQAppID, andDelegate: self)
        permissionArray = NSMutableArray(object: kOPEN_PERMISSION_GET_SIMPLE_USER_INFO)
        
        
        tencentOAuth.authorize(permissionArray as Any! as! [Any]!, inSafari: false)
        
    }
    
    func tencentNeedPerformIncrAuth(_ tencentOAuth: TencentOAuth!, withPermissions permissions: [Any]!) -> Bool {
        tencentOAuth.incrAuth(withPermissions: permissions)
        return false
    }
    
    func tencentNeedPerformReAuth(_ tencentOAuth: TencentOAuth!) -> Bool {
        return true
    }
    
    func tencentDidUpdate(_ tencentOAuth: TencentOAuth) {
        print("增量授权完成")
        if (tencentOAuth.accessToken != nil) && 0 != (tencentOAuth.accessToken as NSString).length {
            // 在这里第三方应用需要更新自己维护的token及有效期限等信息
            // **务必在这里检查用户的openid是否有变更，变更需重新拉取用户的资料等信息** _labelAccessToken.text = tencentOAuth.accessToken;
            
        }
        else {
            print("增量授权不成功，没有获取accesstoken")
        }
    }
    
    func tencentFailedUpdate(_ reason: UpdateFailType) {
        switch reason {
        case kUpdateFailNetwork:
            print("增量授权失败，无网络连接，请设置网络");
            break
        case kUpdateFailUserCancel:
            print("增量授权失败，用户取消授权");
            break
        case kUpdateFailUnknown:
            print("增量授权失败，用户取消授权");
            break
        default:
            print("增量授权失败，未知错误");
            break
            
        }
    }
    
    func getUserInfoResponse(_ response: APIResponse!) {
        
        guard let dic = response.jsonResponse as? [String :AnyObject?] else {
            return
        }
        
        let qqInfoData = dic as NSDictionary
        
        if qqInfoData.count == 0 {
            return
        }
            

        print(qqInfoData)
        
        //将qq头像、昵称写入本地
        let qqHeadImgUrl = qqInfoData["figureurl_qq_2"] as! String
        let qqNickname = qqInfoData["nickname"] as! String
        print("TTTTTTTTTT")
        print("qq头像",qqHeadImgUrl)
        print("qq昵称",qqNickname)
        print("openID",self.qqOpenID)
        
        let qqDelegateData = ["qqOPENID" : self.qqOpenID,
                              "qqNICKNAME" : qqNickname,
        "qqHEADIMGURL" : qqHeadImgUrl] as NSDictionary
        
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "qqdelegate"), object: self, userInfo: qqDelegateData as? [AnyHashable : Any])

    }
    
    func qqShare() -> Void {
        let url = NSURL(string: "http://www.baidu.com")
        let picUrl = NSURL(string: "http://www.baidu.com")
        
        let img = QQApiNewsObject.object(with: url as URL!, title: "测试", description: "测试", previewImageURL: picUrl as URL!)
        
        let req = SendMessageToQQReq(content: img as! QQApiObject!)
        let sent = QQApiInterface.send(req)
        
        handleSendResult(sendResult: sent)

    }
    
    func handleSendResult(sendResult:QQApiSendResultCode) -> Void {
        switch sendResult {
        case EQQAPIAPPNOTREGISTED:
            let alert = UIAlertView(title: "Erroe", message:"App未注册", delegate: self, cancelButtonTitle: "取消")
            alert.show()
            break
        case EQQAPIMESSAGECONTENTINVALID:
            let alert = UIAlertView(title: "Erroe", message:"发送参数错误", delegate: self, cancelButtonTitle: "取消")
            alert.show()
            break
        case EQQAPIMESSAGECONTENTNULL:
            let alert = UIAlertView(title: "Erroe", message:"发送参数错误", delegate: self, cancelButtonTitle: "取消")
            alert.show()
            break
        case EQQAPIMESSAGETYPEINVALID:
            let alert = UIAlertView(title: "Erroe", message:"发送参数错误", delegate: self, cancelButtonTitle: "取消")
            alert.show()
            break
        case EQQAPIQQNOTINSTALLED:
            let alert = UIAlertView(title: "Erroe", message:"未安装手机qq", delegate: self, cancelButtonTitle: "取消")
            alert.show()
            break
        case EQQAPIQQNOTSUPPORTAPI:
            let alert = UIAlertView(title: "Erroe", message:"API接口不支持", delegate: self, cancelButtonTitle: "取消")
            alert.show()

            break
        case EQQAPISENDFAILD:
            let alert = UIAlertView(title: "Erroe", message:"发送失败", delegate: self, cancelButtonTitle: "取消")
            alert.show()
            
            break
        case EQQAPIVERSIONNEEDUPDATE:
            let alert = UIAlertView(title: "Erroe", message:"当前QQ版本太低，需要更新", delegate: self, cancelButtonTitle: "取消")
            alert.show()
            
            break
            
        default:
            break
        }
    }
}

extension QQTool {
    func alertSuccess(message:String) -> Void {
        let alert = UIAlertView(title: "提示", message:message, delegate: self, cancelButtonTitle: "确定")
        alert.show()
    
    }
    func alertFail(message:String) -> Void {
        let alert = UIAlertView(title: "提示", message:message, delegate: self, cancelButtonTitle: "确定")
        alert.show()
    }

}


